package com.mars.module.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mars.common.response.PageInfo;
import com.mars.framework.context.ContextUserInfoThreadHolder;
import com.mars.framework.exception.ServiceException;
import com.mars.module.system.entity.SysRole;
import com.mars.module.system.entity.SysUser;
import com.mars.module.system.entity.SysUserRole;
import com.mars.module.system.mapper.SysUserMapper;
import com.mars.module.system.mapper.SysUserRoleMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.mars.module.admin.request.SysFarmerAttestationRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import com.mars.module.admin.mapper.SysFarmerAttestationMapper;
import org.springframework.beans.BeanUtils;
import com.mars.module.admin.entity.SysFarmerAttestation;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mars.module.admin.service.ISysFarmerAttestationService;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 农户认证业务层处理
 *
 * @author mars
 * @date 2024-04-09
 */
@Slf4j
@Service
@AllArgsConstructor
public class SysFarmerAttestationServiceImpl implements ISysFarmerAttestationService {

    private final SysFarmerAttestationMapper baseMapper;
    private final SysUserMapper userMapper;
    private final SysUserRoleMapper roleMapper;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysFarmerAttestation add(SysFarmerAttestationRequest request) {
        SysFarmerAttestation entity = SysFarmerAttestation.builder().build();
        BeanUtils.copyProperties(request, entity);
        Long userId = ContextUserInfoThreadHolder.get().getId();
        SysUser sysUser = userMapper.selectById(userId);
        if (!request.getName().equals(sysUser.getUserName())) {
            throw new ServiceException("用户只能为自己申请认证！");
        }
        Long l = baseMapper.selectCount(new QueryWrapper<SysFarmerAttestation>().eq("user_id", userId));
        if (l > 0) {
            throw new ServiceException("该用户已经认证为农户！");
        }
        entity.setUserId(userId);
        baseMapper.insert(entity);
        //认证成功后赋予农户的权限
        SysUserRole userRole = roleMapper.selectOne(new QueryWrapper<SysUserRole>().eq("user_id", userId));
        if (userRole == null) {
            userRole = new SysUserRole();
            userRole.setRoleId(1227326979276013568L);
            userRole.setUserId(userId);
            userRole.setCreateTime(LocalDateTime.now());
            userRole.setUpdateTime(LocalDateTime.now());
            roleMapper.insert(userRole);
        } else {
            userRole.setRoleId(1227326979276013568L);
            roleMapper.updateById(userRole);
        }
        return entity;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(Long id) {
        return baseMapper.deleteById(id) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteBatch(List<Long> ids) {
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(SysFarmerAttestationRequest request) {
        SysFarmerAttestation entity = SysFarmerAttestation.builder().build();
        BeanUtils.copyProperties(request, entity);
        return baseMapper.updateById(entity) > 0;
    }

    @Override
    public SysFarmerAttestation getById(Long id) {
        return baseMapper.selectById(id);
    }

    @Override
    public PageInfo<SysFarmerAttestation> pageList(SysFarmerAttestationRequest request) {
        Page<SysFarmerAttestation> page = new Page<>(request.getPageNo(), request.getPageSize());
        LambdaQueryWrapper<SysFarmerAttestation> query = this.buildWrapper(request);
        IPage<SysFarmerAttestation> pageRecord = baseMapper.selectPage(page, query);
        return PageInfo.build(pageRecord);
    }


    @Override
    public List<SysFarmerAttestation> list(SysFarmerAttestationRequest request) {
        LambdaQueryWrapper<SysFarmerAttestation> query = this.buildWrapper(request);
        return baseMapper.selectList(query);
    }

    private LambdaQueryWrapper<SysFarmerAttestation> buildWrapper(SysFarmerAttestationRequest param) {
        LambdaQueryWrapper<SysFarmerAttestation> query = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(param.getCardNo())) {
            query.like(SysFarmerAttestation::getCardNo, param.getCardNo());
        }
        if (StringUtils.isNotBlank(param.getName())) {
            query.like(SysFarmerAttestation::getName, param.getName());
        }
        return query;
    }

}
